//获取应用实例
const app = getApp();

Page({
    data: {
      is_distribution_price_edit:true,
        sel_text: {
            season_name: '',
            choose_style_name: '',
            choose_time_name: '',
            choose_cate_name: '',
            outgoing_user_name: '',
            design_user:'',
            origin_text:'请选择'
        },
        table_scroll_left: 0,
        table_head: [
          {id: 1, name: '件数', field: 'num', is_checked: true, width: 100, show_user: [0]},
         
          {id: 3, name: '采购价', field: 'purchase_price', is_checked: true, width:110, show_user: [0]},
          {id: 4, name: '零售价', field: 'sale_price', is_checked: true, width: 100, show_user: [0]},
          {id: 5, name: '分销价', field: 'distribution_price', is_checked: true, width: 100, show_user: [0]},
          {id: 2, name: '交期', field: 'delivery_time', is_checked: true, width: 100, show_user: [0]},
        ],
        purchase_table_head: [
          {id: 1, name: '件数', field: 'plan_total_num', is_checked: true, width: 100, show_user: [0]},
          {id: 6, name: '铺货区域', field: 'paving_area', is_checked: true, width:110, show_user: [0]},
          {id: 3, name: '采购价', field: 'purchase_price', is_checked: true, width:110, show_user: [0]},
          {id: 4, name: '零售价', field: 'sale_price', is_checked: true, width: 100, show_user: [0]},
          {id: 5, name: '分销价', field: 'distribution_price', is_checked: true, width: 100, show_user: [0]},
          {id: 2, name: '交期', field: 'expected_completion_date', is_checked: true, width: 100, show_user: [0]},
        ],
        table_head_goods: [
          {id: 1, name: '货号', field: 'goods_no', is_checked: false, width: 100, show_user: [0]},
          {id: 2, name: '颜色', field: 'color_name', is_checked: false, width: 100, show_user: [0]},
          // {id: 3, name: '采购价', field: 'purchase_price', is_checked: true, width:110, show_user: [0]},
          {id: 4, name: '零售价', field: 'sale_price', is_checked: true, width: 100, show_user: [0]},
          {id: 5, name: '分销价', field: 'distribution_price', is_checked: true, width: 100, show_user: [0]},
        ],
        template_goods: [
        ],
        current:"tab1",
        tempFiles: [],
        deleteActionsheet: false,
        delete_groups: [
            { text: '删除图片', value: 1 },
            { text: '前移图片', value: 2 },
            { text: '后移图片', value: 3 }
        ],

        now_action_index: -1,
        upload_file: [],
        sel_color_list: [],
        formData: {
            template_no: '',
            template_name: '',
            thickness: '',
            template_type: '',
            template_style: '',
            // bd_id: 0,
            sale_price: "",
            // year: 2023,
            // season: 0,
            distribution_price: '',
            purchase_price: '',
            shipping_remark: '',
            selling_point: '', // 卖点
            age_name: '',
            faction_name: '',
            outgoing_user: 0,
            outgoing_factory: '',

            one_style_id: 0, // 一级风格
            three_style_id: 0, // 三级风格
            goods_origin: 0, // 三级风格
            design_user: "", // 三级风格

        },
        web_data: null,
        band_list: [],
        template_id: 0,
        season_list: [
            { id: 1, name: '春季', value: 1 },
            { id: 2, name: '夏季', value: 2 },
            { id: 3, name: '秋季', value: 3 },
            { id: 4, name: '冬季', value: 4 },
            { id: 5, name: '通季', value: 5 },
        ],
        thick_list: [],
        age_list: [],
        faction_list: [],
        one_style_list: [], // 一级风格下拉
        three_style_list: [], // 三级风格下拉
        pattern_list: [], // 使用接口数据
        origin_list:[],
        secondStyle_list:[],//二级风格
        // 风格分类
        style_show_data: [],
        style_all_data: [],
        sel_style_arr: [0, 0, 0],
        choose_style_index_arr: [0, 0, 0],
        choose_style_id_arr: [0, 0, 0],
        // 时间分类
        time_show_data: [],
        time_all_data: [],
        sel_time_arr: [0, 0, 0],
        choose_time_index_arr: [0, 0, 0],
        choose_time_id_arr: [0, 0, 0],
        // 商品分类
        cate_show_data: [],
        cate_all_data: [],
        sel_cate_arr: [0, 0, 0],
        choose_cate_index_arr: [0, 0, 0],
        choose_cate_id_arr: [0, 0, 0],
        // 外发人
        person_list: [],
        // 买手
        buyer_list: [],
        buyer_list_column:[],
        // 外发工厂
        is_show_half: false,
        is_show_shade: false,
        factory_list: [],
        factory_total: 0,
        factory_page: 0,
        factory_keywords: '',
        choose_factory: [],

        // 货品供应商
        is_show_half2: false,
        is_show_shade2: false,
        factory_list2: [],
        factory_list_column2: [],
        factory_total2: 0,
        factory_page2: 0,
        factory_keywords2: '',
        choose_factory2: [],
        TypeOptions2: [],
        TypeOptions2Col:{},

        /**生产计划**/
        batchList: [],
        batch_form_config: {//计划弹窗
            show: false,
        },
        batch_supply_form_config: {//计划弹窗的供应商弹窗
            is_show_choose_supplier: false,
            is_shade_screen: false,
        },
        batch_form: {
            // id: 0,
            // batch_name: '',
            // template_cost: '',
            // factory_id: 0,
            // SupplyNa: "",
            // grade_category: '',
            // skus: [],
        },
        /**生产计划**/

        /**生产计划**/
        purchaseList: [],
        purchase_form_config: {//计划弹窗
            show: false,
        },
        purchase_supply_form_config: {//计划弹窗的供应商弹窗
            is_show_choose_supplier: false,
            is_shade_screen: false,
        },
        purchase_form: {
            // id: 0,
            // batch_name: '',
            // template_cost: '',
            // factory_id: 0,
            // SupplyNa: "",
            // grade_category: '',
            // skus: [],
        },
        /**生产计划**/

        is_show_shade3: false,
    },
    // 表格滑动结束
    tr_boxs_scroll_end: function (e) {
      var __this = this;
      setTimeout(function () {
          __this.setData({
              table_scroll_left: e.detail.scrollLeft
          });
      }, 180);
  },
    onLoad: function (options) {
        // 设置标题
        wx.setNavigationBarTitle({
            title: '创建样板'
        });
        this.get_default_data([]);  // 获取默认数据
        // 获取上传标识
        this.get_web_config();
        // 获取风格分类
        this.get_style_list();
        this.get_one_style_list(); // 获取一级风格数据
        // 获取时间分类
        this.get_time_list();
        // 获取分类
        this.get_cate_list();
        // 获取外发人
        this.get_person_list();
           // 获取买手
           this.get_buyer_list();
        // 获取外发工厂
        this.get_factory_list();
        // 获取选项
        this.get_type_options();
        this.is_distribution_price_edit();
        
        // 如果是编辑的话
        if (options.template_id != undefined && options.template_id > 0) {
            // 重设标题
            wx.setNavigationBarTitle({
                title: '编辑样板'
            });
            this.setData({
                template_id: options.template_id
            });
            console.log(options.template_id)
            // 获取样板详情
            this.get_template_detail();
        }
    },

    // 获取样板详情
    get_template_detail: function () {
        var result = app.request_api('admin/Template/edit', {
            template_id: this.data.template_id
        }, true, 'GET');
        result.then(res => {
          this.get_default_data(res.row.category_id);  // 获取默认数据
            if (res.row.outgoing_factory != null && res.row.outgoing_factory != '') {
                this.data.choose_factory = res.row.outgoing_factory.split(',');
            }
            this.setData({
                template_goods:res.row.sku_data.length > 0 ? res.row.sku_data : res.row.sku ,
                [`formData.purchase_price`]: res.row.purchase_price,
                [`formData.distribution_price`]: res.row.distribution_price,
                [`formData.sale_price`]: res.row.sale_price,
                [`formData.template_name`]: res.row.template_name,
                [`formData.template_no`]: res.row.template_no,
                [`formData.thickness`]: res.row.thickness,
                [`formData.template_type`]: res.row.template_type,
                [`formData.age_name`]: res.row.age_name,
                [`formData.template_style`]: res.row.template_style,
                [`formData.faction_name`]: res.row.faction_name,
                [`formData.shipping_remark`]: res.row.shipping_remark != null ? res.row.shipping_remark : '',
                [`formData.selling_point`]: res.row.selling_point != null ? res.row.selling_point : '', // 卖点
                
                [`formData.outgoing_user`]: res.row.outgoing_user != null ? res.row.outgoing_user : 0,
                [`formData.outgoing_factory`]: res.row.outgoing_factory,
                [`formData.template_cost`]: res.row.template_cost,
                [`formData.real_template_cost`]: res.row.real_template_cost,

                [`formData.one_style_name`]: res.row.one_style_name, // 一级风格名称
                [`formData.three_style_name`]: res.row.three_style_name, // 三级风格名称 
                [`formData.one_style_id`]: res.row.one_style_id, // 一级风格ID
                [`formData.three_style_id`]: res.row.three_style_id, // 三级风格ID
                [`formData.goods_origin`]: res.row.goods_origin, // 三级风格ID
                [`formData.buyer`]: res.row.buyer, // 三级风格ID
                [`formData.design_user`]: res.row.design_user,
                choose_factory: this.data.choose_factory,
                // [`formData.season_name`]: season_name,
                // [`formData.bd_id`]: res.row.bd_id,
                // [`formData.year`]: res.row.year,
                // [`formData.season`]: res.row.season,
                // [`sel_text.band_text`]: res.row.band_name,
                choose_cate_id_arr: res.row.category_id,
                choose_time_id_arr: res.row.time_category_id,
                choose_style_id_arr: res.row.style_category_id,
                [`sel_text.choose_cate_name`]: res.row.category_name,
                [`sel_text.choose_time_name`]: res.row.time_category_name,
                [`sel_text.choose_style_name`]: res.row.style_category_name,
                [`sel_text.outgoing_user_name`]: res.row.outgoingUser != null ? res.row.outgoingUser.realname : '',
                [`sel_text.design_user`]: res.row.design_user,
                [`sel_text.origin_text`]: res.row.goods_origin_text,
            });
            // 组装颜色
            if (res.row.sku.length > 0) {
                var sel_color_list = [];
                res.row.sku.forEach(function (item, index) {
                    sel_color_list.push({
                        id: item.color_id,
                        is_checked: true,
                        name: item.color,
                        num: item.quantity,
                    });
                });
                this.setData({
                    sel_color_list: sel_color_list
                })
            }
            // 组装图片
            if (res.row.template_images.length > 0) {
                var tempFiles = [];
                res.row.template_images.forEach(function (item, index) {
                    tempFiles.push({
                        tempFilePath: item,
                        is_old_file: 1
                    });
                });
                this.setData({
                    tempFiles: tempFiles
                });
            }
        });
    },

    // 获取上传标识
    get_web_config: function () {
        // 发起请求
        var result = app.request_api('admin/index/index', {}, false, 'GET');
        result.then(res => {
            console.log(res)
            this.setData({
                web_data: res
            });
        });
        return result;
    },

    // 获取外发工厂
    get_factory_list: function (is_search = 0) {
        var __this = this;
        // 验证
        if ((this.data.factory_list.length >= this.data.factory_total) && this.data.factory_page > 0) {
            return false;
        }
        // 发起请求
        var result = app.request_api('admin/Factory/index', {
            page: __this.data.factory_page + 1,
            quick_search: __this.data.factory_keywords,
            limit: 100,
        }, false);
        result.then(res => {
            console.log(res)
            if (is_search == 1) {
                __this.setData({
                    factory_list: [],
                    factory_page: 0,
                    factory_total: 0
                })
            }
            __this.setData({
                factory_list: __this.data.factory_list.concat(res.list),
                factory_page: this.data.factory_page + 1,
                factory_total: res.total
            })
        });
    },

    // 搜索工厂
    halfBottomSearch: function (events) {
        var keywords = events.detail.value.trim();
        this.setData({
            factory_keywords: keywords,
            factory_list: [],
            factory_page: 0,
            factory_total: 0
        });
        this.get_factory_list(1);
    },

    // 选择加工厂时
    choose_factory: function (events) {
        var index = events.currentTarget.dataset.index;
        this.data.choose_factory.push(this.data.factory_list[index].SupplyNa);
        this.setData({
            choose_factory: this.data.choose_factory,
            [`formData.outgoing_factory`]: this.data.choose_factory.join(',')
        })
    },

    // 删除选择项
    DeleteChoose: function (events) {
        var index = events.currentTarget.dataset.index;
        console.log(index)
        this.data.choose_factory.splice(index, 1);
        this.setData({
            choose_factory: this.data.choose_factory,
            [`formData.outgoing_factory`]: this.data.choose_factory.join(',')
        });
    },

    // 添加选项
    add_factory: function (events) {
        var keywords = this.data.factory_keywords.trim();
        if (keywords == '') {
            wx.showToast({
                title: '请输入后再添加',
                icon: 'none',
                duration: 1500,
            });
            return false;
        }
        this.data.choose_factory.push(keywords);
        this.setData({
            choose_factory: this.data.choose_factory,
            factory_keywords: '',
            factory_list: [],
            factory_page: 0,
            factory_total: 0,
            [`formData.outgoing_factory`]: this.data.choose_factory.join(',')
        });
        this.get_factory_list();
    },

    // 关闭半屏
    close_half: function (e) {
        this.setData({
            is_show_shade: false,
            is_show_half: false
        })
    },

    // 打开半屏
    open_half: function (e) {
        this.setData({
            is_show_shade: true,
            is_show_half: true
        })
    },

    // 获取默认数据
    get_default_data: function (cate_arr) {
        // 发起请求
        var result = app.request_api('admin/Dict/addInit', {
            'cate_arr': cate_arr, // 分类数组
            'type': 1,
            'keys': ['secondStyle','pattern', 'ageName', 'factionName', 'thickness','designUser', 'goodsOrigin'],
        }, false, 'POST');
        result.then(res => {
            this.setData({
                pattern_list: res.select_list.pattern,
                age_list: res.select_list.ageName,
                faction_list: res.select_list.factionName,
                thick_list: res.select_list.thickness,
                design_list: res.select_list.designUser,
                origin_list: res.select_list.goodsOrigin,
                secondStyle_list: res.select_list.secondStyle,
            });
        });
    },

    // 获取风格分类
    get_style_list: function () {
        // 发起请求
        var result = app.request_api('admin/GoodsStyleCategory/getTreeAll', {}, false, 'GET');
        result.then(res => {
            this.setData({
                style_show_data: [res, res[0].children, res[0].children[0].children],
                style_all_data: res
            });
        });
    },

    // 获取一级风格+三级风格分类
    get_one_style_list: function () {
      // 发起请求
      var result = app.request_api('admin/GoodsStyleCategory/selectItem', {}, false, 'GET');
      result.then(res => {
        console.log('ant_res',res)
          this.setData({
            one_style_list: res.list,
            three_style_list: res.three_list, 
          });
      });
  },

    // 获取时间分类
    get_time_list: function () {
        // 发起请求
        var result = app.request_api('admin/GoodsTimeCategory/timeTree', {}, false, 'GET');
        result.then(res => {
            this.setData({
                time_show_data: [res, res[0].child, res[0].child[0].child],
                time_all_data: res
            });
        });
    },

    // 获取分类
    get_cate_list: function () {
        // 发起请求
        var result = app.request_api('admin/GoodsCategory/categoryTree', {
            is_mini: 1
        }, false, 'GET');
        result.then(res => {
            this.setData({
                cate_show_data: [res, res[0].childnode, res[0].childnode[0].childnode],
                cate_all_data: res
            });
        });
    },

    // 获取外发人
    get_person_list: function () {
        // 发起请求
        var result = app.request_api('admin/template/getOutgoings', {}, false, 'GET');
        result.then(res => {
            console.log(res)
            this.setData({
                person_list: res.list
            });
        });
    },

    // 获取外发人
    get_buyer_list: function () {
      // 发起请求
      
      var result = app.request_api('admin/auth.admin/user_categorys', {group_id:5,limit:99}, false, 'POST');
      result.then(res => {
        let buyer_list_column = [];
        res.forEach((v,k)=>{
          buyer_list_column[v.id] = v.name
        })
          this.setData({
            buyer_list: res,
            buyer_list_column:buyer_list_column
          });
      });
  },

    // 波段改变时
    bandChange: function (e) {
        // 设置已选择的项
        this.setData({
            [`formData.bd_id`]: this.data.band_list[e.detail.value].band_id,
            [`sel_text.band_text`]: this.data.band_list[e.detail.value].band_name
        });
    },
    // 波段改变时
    marketSpuChange: function (e) {
        console.log(this.data.origin_list)
        console.log(e.detail.value)
        // 设置已选择的项
        this.setData({
            [`formData.goods_origin`]: e.detail.value,
            [`sel_text.origin_text`]: this.data.origin_list[e.detail.value].name
        });
    },
    onChange(e){
      this.setData({
        current:e.detail.key
      })
    },
    // 季节改变时
    seasonChange: function (e) {
        this.setData({
            [`formData.season`]: this.data.season_list[e.detail.value].value,
            [`sel_text.season_name`]: this.data.season_list[e.detail.value].name
        });
    },

    // 外发人改变时
    personChange: function (e) {
        this.setData({
            [`formData.outgoing_user`]: this.data.person_list[e.detail.value].uid,
            [`sel_text.outgoing_user_name`]: this.data.person_list[e.detail.value].realname,
        });
    },

    // 买手改变时
    buyerChange: function (e) {
      this.setData({
          [`formData.data_type`]: this.data.buyer_list[e.detail.value].id,
          // [`sel_text.data_type_name`]: this.data.buyer_list[e.detail.value].realname,
      });
  },

  
    // 二级风格改变时
    secondStyleChange: function (e) {
      this.setData({
          [`formData.second_style`]: this.data.secondStyle_list[e.detail.value].value,
          // [`sel_text.data_type_name`]: this.data.buyer_list[e.detail.value].realname,
      });
  },

    // 外发人改变时
    designChange: function (e) {
        this.setData({
            [`formData.design_user`]: this.data.design_list[e.detail.value].name,
            [`sel_text.design_user`]: this.data.design_list[e.detail.value].name,
        });
    },

    // 改变适龄段时
    ageChange: function (e) {
        // 设置已选择的项
        this.setData({
            [`formData.age_name`]: this.data.age_list[e.detail.value].name
        });
    },

    // 时尚度
    faChange: function (e) {
        // 设置已选择的项
        this.setData({
            [`formData.faction_name`]: this.data.faction_list[e.detail.value].name
        });
    },

    // 一级风格
    oneStyleChange: function (e) { 
      let thatData = this.data.one_style_list[e.detail.value]
      this.setData({  // 设置已选择的项
          [`formData.one_style_name`]: thatData.style_category_name,
          [`formData.one_style_id`]: thatData.id
      });
    },

    // 三级风格
    threeStyleChange: function (e) { 
      let thatData = this.data.three_style_list[e.detail.value]
      this.setData({  // 设置已选择的项
          [`formData.three_style_name`]: thatData.label,
          [`formData.three_style_id`]: thatData.value,
      });
  },

    // 厚薄度改变时
    thickChange: function (e) {
        this.setData({
            [`formData.thickness`]: this.data.thick_list[e.detail.value].name
        });
    },

    // 版型改变时
    patternChange: function (e) {
        this.setData({
            [`formData.template_type`]: this.data.pattern_list[e.detail.value].name
        });
    },

    // 输入框改变
    formInputChange(e) {
        const { field } = e.currentTarget.dataset
        this.setData({
            [`formData.${field}`]: e.detail.value.trim()
        });
    },

    // 选择颜色
    ChooseColor: function (events) {
        var __this = this;
        // 打开选择颜色页面
        wx.navigateTo({
            url: '/pages/choose_color/choose_color',
            events: {
                // 当选择完成时
                changeData: function (data) {
                    console.log(data);
                    __this.setData({
                        sel_color_list: data
                    });
                }
            },
            success: function (res) {
                // 向被打开页面传送数据
                res.eventChannel.emit('acceptDataFromOpenerPage', {
                    sel_list: __this.data.sel_color_list,
                    purchase_table_head: __this.data.purchase_table_head
                });
            }
        });
    },
    submitPriceUpdate(){
      wx.showLoading({
        title: '修改中',
      })
      var template_goods = this.data.template_goods;
      // 发起请求
      var result = app.request_api('admin/ScmGoods/updateGoods ', {
        goods:template_goods
      }, false, 'post',{},true);
      result.then(res => {
          if(res.code==1){
            wx.showToast({
              title: res.msg,
              duration:2000,
            })
          }
      }).finally(()=>{
        wx.hideLoading();
      })
    },
    // 当输入生产数量时
    selInputChange: function (e) {
        var index = e.currentTarget.dataset.index;
        var field = e.currentTarget.dataset.field;
        this.data.sel_color_list[index][field] = e.detail.value;
        this.setData({
            sel_color_list: this.data.sel_color_list
        })
    },

    // 取消选择
    chooseDel: function (e) {
        var index = e.currentTarget.dataset.index;
        this.data.sel_color_list.splice(index, 1);
        // 重置data
        this.setData({
            sel_color_list: this.data.sel_color_list
        });
    },

    // 提交
    formSubmit: function (e) {
        var __this = this;
        // 加载条
        wx.showLoading({
            title: '正在提交',
            mask: true
        })
        // 验证是否有图片要上传
        if (__this.data.tempFiles.length > 0) {
            // 重新获取上传token
            var upconfig = __this.get_web_config();
            upconfig.then(res => {
                __this.upload_images_fun();
            });
        } else {
            // 调用发布方法
            __this.form_submit_fun();
        }
    },

    // 上传图片
    upload_images_fun: function () {
        var __this = this;
        // 重置
        __this.setData({
            upload_file: [],
        });
        var req_arr = [];
        // 上传
        for (var i = 0; i < __this.data.tempFiles.length; i++) {
            var result = app.request_upload('', {
                cdn_url: __this.data.web_data.siteConfig.apiUrl,
                token: __this.data.web_data.siteConfig.upload.token,
                is_old_file: __this.data.tempFiles[i].is_old_file == undefined ? 0 : __this.data.tempFiles[i].is_old_file
            }, __this.data.tempFiles[i].tempFilePath, i, false);
            req_arr.push(result);
            // 处理结果
            result.then(res => {
                // console.log(res)
                __this.data.upload_file[res.for_i] = res;
                __this.setData({
                    upload_file: __this.data.upload_file
                });
            });
        }
        // 全部上传成功后调用
        Promise.all(req_arr).then(res => {
            // console.log(res)
            __this.form_submit_fun();
        }).catch(error => {
            console.log(error);
            wx.hideLoading();
        });
    },

    // 发起请求
    form_submit_fun: function () {
        var __this = this;
        // 组装sku
        var sku_arr = [];
        var color_arr = [];
        if (__this.data.sel_color_list.length > 0) {
            __this.data.sel_color_list.forEach(function (item, index) {
                sku_arr.push({
                    color: item.name,
                    quantity: item.num == '' ? 0 : item.num,
                    delivery_time:item.delivery_time
                });
                color_arr.push(item.name)
            });
        }
        // 组装图片
        var template_images = [];
        if (__this.data.upload_file.length > 0) {
            __this.data.upload_file.forEach(function (item, index) {
                template_images.push(item.file_key);
            });
        }
        // 重新组装
        var req_param = __this.data.formData;
        req_param.sku = sku_arr;
        req_param.color = color_arr;
        req_param.template_images = template_images;
        req_param.size_list = [];
        req_param.zip_list = [];
        req_param.bom_list = [];
        // 分类
        req_param.category_id = this.data.choose_cate_id_arr;
        // 时间分类
        req_param.time_category_id = this.data.choose_time_id_arr;
        // 风格分类
        req_param.style_category_id = this.data.choose_style_id_arr;
        req_param.batch_form = Object.assign({}, this.data.batch_form);
        req_param.purchase_form = Object.assign({}, this.data.purchase_form);
        let skus_batch = this.data.batch_form.skus||[]
        if(skus_batch.length>0){
            let skus = [];
            skus_batch.forEach((v, k) => {
                skus.push({ 
                  color: v.name, 
                  quantity: v.num,
                  delivery_time:v.delivery_time,
                  purchase_price:v.purchase_price,
                  sale_price:v.sale_price,
                  distribution_price:v.distribution_price,
                })
            })
            req_param.batch_form.skus = skus
        }
        // console.log(req_param.batch_form,this.data.batch_form)
        // wx.hideLoading();
        // return;
        var req_url = 'admin/Template/add';
        if (__this.data.template_id > 0) {
            req_param.template_id = __this.data.template_id;
            req_url = 'admin/Template/edit';
            req_param.batch_form = {}
        }
        // 发起请求
        var result = app.request_api(req_url, req_param, false);
        result.then(res => {
            console.log(res)
            // 向上一级页面传递参数
            var eventChannel = __this.getOpenerEventChannel();
            eventChannel.emit('changeData', {});
            // 跳转回前一页
            wx.showModal({
                title: '提示',
                content: res.DiyApiMsg != '' ? res.DiyApiMsg : '提交成功',
                showCancel: false,
                complete() {
                    wx.navigateBack();
                }
            });
        });
        wx.hideLoading();
    },

    // 点击添加图片时
    AddPic: function () {
        var __this = this;
        // 选择图片
        wx.chooseMedia({
            count: 9 - (__this.data.tempFiles.length),
            mediaType: ['image'],
            sourceType: ['album', 'camera'],
            maxDuration: 30,
            sizeType: ['original', 'compressed'],
            camera: 'back',
            success(res) {
                console.log(res);
                // 重设data
                __this.setData({
                    tempFiles: __this.data.tempFiles.concat(res.tempFiles)
                });
            }
        })
    },

    // 预览图片
    PreViewImg: function (events) {
        var __this = this;
        // 数据下标
        var index = events.currentTarget.dataset.index;
        var path = events.currentTarget.dataset.path;
        var file_arr = [];
        // 取出所有图片的链接
        for (var i = 0; i < __this.data.tempFiles.length; i++) {
            file_arr.push(__this.data.tempFiles[i].tempFilePath);
        }
        // 调用
        wx.previewImage({
            current: path, // 当前显示图片的http链接
            urls: file_arr // 需要预览的图片http链接列表
        })
    },

    // 删除或调整图片位置
    DeletePic: function (events) {
        var __this = this;
        // 数据下标
        var index = events.currentTarget.dataset.index;
        // 打开操作表
        this.setData({
            deleteActionsheet: true,
            now_action_index: index
        });
    },

    // 点击删除操作表中某一项时
    DeleteGroupsClick: function (e) {
        var __this = this;
        if (e.detail.value == 1) {
            // 删除图片
            __this.data.tempFiles.splice(__this.data.now_action_index, 1);
            // 重设data
            __this.setData({
                tempFiles: __this.data.tempFiles,
                deleteActionsheet: false,
                now_action_index: -1,
            });
        } else if (e.detail.value == 2) {
            // 前移图片
            if (__this.data.now_action_index == 0) {
                wx.showToast({
                    title: '无需前移',
                    icon: 'none',
                    duration: 1500,
                });
                __this.setData({
                    deleteActionsheet: false,
                });
                return false;
            }
            var pre_one = __this.data.tempFiles[__this.data.now_action_index - 1];
            var now_one = __this.data.tempFiles[__this.data.now_action_index];
            __this.data.tempFiles[__this.data.now_action_index] = pre_one;
            __this.data.tempFiles[__this.data.now_action_index - 1] = now_one;
            // 重设data
            __this.setData({
                tempFiles: __this.data.tempFiles,
                deleteActionsheet: false,
                now_action_index: -1,
            });
        } else if (e.detail.value == 3) {
            // 后移图片
            if ((__this.data.now_action_index + 1) == __this.data.tempFiles.length) {
                wx.showToast({
                    title: '无需后移',
                    icon: 'none',
                    duration: 1500,
                });
                __this.setData({
                    deleteActionsheet: false,
                });
                return false;
            }
            var next_one = __this.data.tempFiles[__this.data.now_action_index + 1]
            var now_one = __this.data.tempFiles[__this.data.now_action_index];
            __this.data.tempFiles[__this.data.now_action_index] = next_one;
            __this.data.tempFiles[__this.data.now_action_index + 1] = now_one;
            __this.setData({
                tempFiles: __this.data.tempFiles,
                deleteActionsheet: false,
                now_action_index: -1,
            });
        }
    },

    // 风格分类值变化时
    StyleValueChange: function (e) {
        // console.log(e);
        var style_show_data = this.data.style_show_data;
        var choose_style_index_arr = e.detail.value;
        var choose_style_name = style_show_data[0][choose_style_index_arr[0]].style_category_name + ' - ' + style_show_data[1][choose_style_index_arr[1]].style_category_name + ' - ' + style_show_data[2][choose_style_index_arr[2]].style_category_name;
        this.setData({
            choose_style_id_arr: [style_show_data[0][choose_style_index_arr[0]].id, style_show_data[1][choose_style_index_arr[1]].id, style_show_data[2][choose_style_index_arr[2]].id],
            choose_style_index_arr: choose_style_index_arr,
            [`sel_text.choose_style_name`]: choose_style_name
        });
    },

    // 风格分类列变化时
    StyleColumnChange: function (e) {
        // console.log(e);
        var style_all_data = this.data.style_all_data;
        var style_show_data = this.data.style_show_data;
        var sel_style_arr = this.data.sel_style_arr;
        var index = e.detail.value;
        if (e.detail.column == 0) {
            // 一级分类改变时
            this.data.style_show_data[1] = style_all_data[index].children;
            this.data.style_show_data[2] = style_all_data[index].children[0].children;
            sel_style_arr = [index, 0, 0];
        }
        if (e.detail.column == 1) {
            // 二级分类改变时
            this.data.style_show_data[2] = style_show_data[1][index].children;
            sel_style_arr[1] = index;
            sel_style_arr[2] = 0;
        }
        if (e.detail.column == 2) {
            // 三级分类改变时
            sel_style_arr[2] = index;
        }
        // 重新渲染
        this.setData({
            style_show_data: this.data.style_show_data,
            sel_style_arr: sel_style_arr
        });
    },

    // 时间分类值变化时
    TimeValueChange: function (e) {
        // console.log(e);
        var time_show_data = this.data.time_show_data;
        var choose_time_index_arr = e.detail.value;
        console.log('aut_time_show_data',time_show_data)
        console.log('aut_choose_time_index_arr',choose_time_index_arr)
        console.log('aut_time_show_data[0][choose_time_index_arr[0]]',time_show_data[0][choose_time_index_arr[0]])

        
        var choose_time_name = time_show_data[0][choose_time_index_arr[0]].label + ' - ' + time_show_data[1][choose_time_index_arr[1]].label + ' - ' + time_show_data[2][choose_time_index_arr[2]].label;
        this.setData({
            choose_time_id_arr: [time_show_data[0][choose_time_index_arr[0]].id, time_show_data[1][choose_time_index_arr[1]].id, time_show_data[2][choose_time_index_arr[2]].id],
            choose_time_index_arr: choose_time_index_arr,
            [`sel_text.choose_time_name`]: choose_time_name
        });
    },

    // 时间分类列变化时
    TimeColumnChange: function (e) {
        // console.log(e);
        var time_all_data = this.data.time_all_data;
        var time_show_data = this.data.time_show_data;
        var sel_time_arr = this.data.sel_time_arr;
        var index = e.detail.value;
        if (e.detail.column == 0) {
            // 一级分类改变时
            this.data.time_show_data[1] = time_all_data[index].child;
            this.data.time_show_data[2] = time_all_data[index].child[0].child;
            sel_time_arr = [index, 0, 0];
        }
        if (e.detail.column == 1) {
            // 二级分类改变时
            this.data.time_show_data[2] = time_show_data[1][index].child;
            sel_time_arr[1] = index;
            sel_time_arr[2] = 0;
        }
        if (e.detail.column == 2) {
            // 三级分类改变时
            sel_time_arr[2] = index;
        }
        // 重新渲染
        this.setData({
            time_show_data: this.data.time_show_data,
            sel_time_arr: sel_time_arr
        });
    },

    // 分类值变化时
    CateValueChange: function (e) {
        // console.log(e);
        var cate_show_data = this.data.cate_show_data;
        var choose_cate_index_arr = e.detail.value;
        var choose_cate_name = cate_show_data[0][choose_cate_index_arr[0]].label + ' - ' + cate_show_data[1][choose_cate_index_arr[1]].label + ' - ' + cate_show_data[2][choose_cate_index_arr[2]].label;

        let choose_cate_id_arr = [cate_show_data[0][choose_cate_index_arr[0]].id, cate_show_data[1][choose_cate_index_arr[1]].id, cate_show_data[2][choose_cate_index_arr[2]].id]
        this.setData({
            choose_cate_id_arr: choose_cate_id_arr,
            choose_cate_index_arr: choose_cate_index_arr,
            [`sel_text.choose_cate_name`]: choose_cate_name
        });
        // 属性值的下拉数据跟着改变
        this.get_default_data(choose_cate_id_arr)
    },

    // 分类列变化时
    CateColumnChange: function (e) {
        // console.log(e);
        var cate_all_data = this.data.cate_all_data;
        var cate_show_data = this.data.cate_show_data;
        var sel_cate_arr = this.data.sel_cate_arr;
        var index = e.detail.value;
        if (e.detail.column == 0) {
            // 一级分类改变时
            this.data.cate_show_data[1] = cate_all_data[index].childnode;
            this.data.cate_show_data[2] = cate_all_data[index].childnode[0].childnode;
            sel_cate_arr = [index, 0, 0];
        }
        if (e.detail.column == 1) {
            // 二级分类改变时
            this.data.cate_show_data[2] = cate_show_data[1][index].childnode;
            sel_cate_arr[1] = index;
            sel_cate_arr[2] = 0;
        }
        if (e.detail.column == 2) {
            // 三级分类改变时
            sel_cate_arr[2] = index;
        }
        // 重新渲染
        this.setData({
            cate_show_data: this.data.cate_show_data,
            sel_cate_arr: sel_cate_arr
        });
    },

    // 采购时间
    bindDateChange: function (e) {
        let index = e.currentTarget.dataset.index
        var bianl = `batch_form.skus[${index}].delivery_time`;
        this.setData({
            [bianl]: e.detail.value
        })
    },
        // 采购时间
        PurchaseBindDateChange: function (e) {
          let index = e.currentTarget.dataset.index
          var bianl = `purchase_form.skus[${index}].expected_completion_date`;
          this.setData({
              [bianl]: e.detail.value
          })
      },

    /**生产计划**/
    saveBatch() {
        // this.data.batch_form.template_id = this.data.template_id;
        // let skus = [];
        // this.data.batch_form.skus.forEach((v, k) => {
        //     skus.push({ color: v.name, quantity: v.num })
        // })
        // this.data.batch_form.skus = skus
        this.hideForm();
    },
    // 当输入生产数量时
    selInputChange2: function (e) {
        var index = e.currentTarget.dataset.index;
        var field = e.currentTarget.dataset.field;
        this.data.batch_form.skus[index][field] = e.detail.value;
        console.log('this.data.batch_form',this.data.batch_form)
        this.setData({
            [`batch_form.skus`]: this.data.batch_form.skus
        })
    },
        // 当输入生产数量时
        purchaseSelInputChange2: function (e) {
          var index = e.currentTarget.dataset.index;
          var field = e.currentTarget.dataset.field;
          this.data.purchase_form.skus[index][field] = e.detail.value;
          console.log('this.data.purchase_form',this.data.purchase_form)
          this.setData({
              [`purchase_form.skus`]: this.data.purchase_form.skus
          })
      },
    // 当输入生产数量时
    selInputChange3: function (e) {
      var index = e.currentTarget.dataset.index;
      var field = e.currentTarget.dataset.field;
      this.data.template_goods[index][field] = e.detail.value;
      this.setData({
          [`template_goods`]: this.data.template_goods
      })
    },
    batch_info_input: function (e) {
        let { field } = e.currentTarget.dataset
        let { value } = e.detail;
        this.setData({
            [`batch_form.${field}`]: value,
        })
    },
    delBatch(){
        this.setData({
            [`batch_form`]: {},
        })
    },
    PurchasedelBatch(){
      this.setData({
          [`purchase_form`]: {},
      })
  },
    // 取消选择
    chooseDel2: function (e) {
        var index = e.currentTarget.dataset.index;
        this.data.batch_form.skus.splice(index, 1);
        // 重置data
        this.setData({
            [`batch_form.skus`]: this.data.batch_form.skus
        });
    },

    chooseDel3: function (e) {
      var index = e.currentTarget.dataset.index;
      this.data.purchase_form.skus.splice(index, 1);
      // 重置data
      this.setData({
          [`purchase_form.skus`]: this.data.purchase_form.skus
      });
  },

    ChooseColor2: function (events) {
        var __this = this;
        // 打开选择颜色页面
        wx.navigateTo({
            url: '/pages/choose_color/choose_color',
            events: {
                // 当选择完成时
                changeData: function (data) {
                    __this.setData({
                        [`batch_form.skus`]: data
                    });
                }
            },
            success: function (res) {
                // 向被打开页面传送数据
                res.eventChannel.emit('acceptDataFromOpenerPage', {
                    sel_list: __this.data.batch_form.skus||[],
                    purchase_table_head: __this.data.purchase_table_head
                });
            }
        });
    },
    PurchaseChooseColor2: function (events) {
      var __this = this;
      // 打开选择颜色页面
      wx.navigateTo({
          url: '/pages/choose_color/choose_color',
          events: {
              // 当选择完成时
              changeData: function (data) {
                  __this.setData({
                      [`purchase_form.skus`]: data
                  });
              }
          },
          success: function (res) {
              // 向被打开页面传送数据
              res.eventChannel.emit('acceptDataFromOpenerPage', {
                  sel_list: __this.data.purchase_form.skus||[],
                  purchase_table_head: __this.data.purchase_table_head,
              });
          }
      });
  },
    showForm(e) {
        // let index = e.currentTarget.dataset.index
        // let id = e.currentTarget.dataset.id
        // this.get_factory_list();
        // this.get_type_options();
        this.setData({
            [`batch_form_config.show`]: true,
            is_show_shade3: true
        });
    },
    purchaseShowForm(e) {
      // let index = e.currentTarget.dataset.index
      // let id = e.currentTarget.dataset.id
      //
      // this.get_factory_list();
      // this.get_type_options();
      this.setData({
          [`purchase_form_config.show`]: true,
          is_show_shade3: true
      });
  },
  purchaseHideForm() {
        this.setData({
            [`purchase_form_config.show`]: false,
            is_show_shade3: false,
        });
    },
    showForm(e) {
      // let index = e.currentTarget.dataset.index
      // let id = e.currentTarget.dataset.id
      //
      // this.get_factory_list();
      // this.get_type_options();
      this.setData({
          [`batch_form_config.show`]: true,
          is_show_shade3: true
      });
  },
    hideForm() {
        this.setData({
            [`batch_form_config.show`]: false,
            is_show_shade3: false,
        });
    },
    TypeOptionsChange(e) {
        let index = e.detail.value
        let value = this.data.TypeOptions2[index].label
        this.setData({
            [`batch_form.batch_name`]: value
        })
    },

    PurchaseTypeOptionsChange(e) {
      let index = e.detail.value
      let value = this.data.TypeOptions2[index].value
      this.setData({
          [`purchase_form.purchase_type`]: value
      })
  },
  
  is_distribution_price_edit() {
    var result = app.request_api('admin/template/is_distribution_price_edit', {
    }, false);
    result.then(res => {
      this.setData({
        is_distribution_price_edit:res.is_edit
      })
    })
  },
    get_type_options() {
        var result = app.request_api('admin/ProductBatch/getTypeOptions', {
        }, false);
        let TypeOptions2Col = {};
        result.then(res => {
            let data = res.list
            data.forEach((v,k)=>{
              TypeOptions2Col[v.value] = v.label
            })
            this.setData({
                TypeOptions2: data,
                TypeOptions2Col:TypeOptions2Col
            })
        });
    },

    // 关闭半屏3
    close_half3: function (e) {
        this.setData({
            is_show_shade3: false,
            [`batch_form_config.show`]: false,
            [`purchase_form_config.show`]: false
        })
    },
    

    // 打开半屏
    open_half2: function (e) {
        this.setData({
            is_show_shade2: true,
            is_show_half2: true
        })
    },
    // 关闭半屏
    close_half2: function (e) {
        this.setData({
            is_show_shade2: false,
            is_show_half2: false
        })
    },
    // 搜索工厂
    halfBottomSearch2: function (events) {
        var keywords = events.detail.value.trim();
        this.setData({
            factory_keywords: keywords,
            factory_list: [],
            factory_page: 0,
            factory_total: 0
        });
        this.get_factory_list(1);
    },
    // 选择加工厂时
    choose_factory2: function (events) {
        var index = events.currentTarget.dataset.index;
        var id = this.data.factory_list[index].id
        var SupplyNa = this.data.factory_list[index].SupplyNa
        let choose_factory2 = []
        choose_factory2.push(SupplyNa);
        this.setData({
            choose_factory2: choose_factory2,
            [`batch_form.factory_id`]: id,
            [`purchase_form.supply_id`]: id,
            [`batch_form.SupplyNa`]: SupplyNa,
            is_show_shade2: false,
            is_show_half2: false
        })
    },

    // 删除选择项
    DeleteChoose2: function (events) {
        var index = events.currentTarget.dataset.index;
        console.log(index)
        this.data.choose_factory2.splice(index, 1);
        this.setData({
            choose_factory2: this.data.choose_factory2,
            [`formData.outgoing_factory`]: this.data.choose_factory2.join(',')
        });
    },
    /** 生产计划 **/

    // 新增供应商
    add_supply: function (e) {
        const __this = this;
        // 跳转到添加供应商界面
        wx.navigateTo({
            url: '/pages/supply_add/supply_add',
            events: {
                // 当添加完成时
                changeData: function (data) {
                    // 重新加载数据
                    __this.setData({
                        factory_keywords: data.simple_name,
                        factory_list: [],
                        factory_page: 0,
                        factory_total: 0
                    });
                    __this.get_factory_list(1);
                }
            }
        });
    },
})
